<!-- ClientNursingDialog.vue -->
<template>
  <el-dialog v-model="visible" title="选择客户" width="60%">
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="客户名:">
        <el-input v-model="searchForm.name" placeholder="请输入客户名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="default" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" v-loading="loading" style="width: 100%;">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="name" label="客户名" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="success" size="small" @click="selectClient(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.cur"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      :page-sizes="[5, 10]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px;" />
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import {inject} from 'vue'
const axios = inject("axios")

import { ElMessage } from 'element-plus'

const visible = ref(false)
const searchForm = ref({ name: '' })
const tableData = ref([])
const loading = ref(false)
const pagination = ref({
  cur: 1,
  size: 5,
  total: 0
})

const open = () => {
  visible.value = true
  fetchData(1)
}

const fetchData = async (page) => {
  loading.value = true
  try {
    const res = await axios.get('/client/pageClientWithoutNursingLevel', {
      params: {
        cur: page,
        number: pagination.value.size,
        name: searchForm.value.name || ''
      }
    })
    if (res.data.status === 200) {
      tableData.value = res.data.data
      pagination.value.total = res.data.total || 0
    }
  } catch (e) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.cur = 1
  fetchData(1)
}

const handleReset = () => {
  searchForm.value.name = ''
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.value.size = size
  fetchData(1)
}

const handleCurrentChange = (page) => {
  pagination.value.cur = page
  fetchData(page)
}

const selectClient = (client) => {
  ElMessage.success(`已选择客户「${client.name}」`)
  visible.value = false
}

defineExpose({ open })
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
